import puppeteer from 'puppeteer';
import fs from 'fs';

async function poweroneLogin() {
  const url = 'https://sharing.powerone.cn:8921/';
  
  try {
    console.log(`正在启动浏览器并访问: ${url}`);
    
    // 启动浏览器
    const browser = await puppeteer.launch({
      headless: false,
      ignoreHTTPSErrors: true,
      defaultViewport: { width: 1920, height: 1080 },
      args: [
        '--ignore-certificate-errors',
        '--ignore-certificate-errors-spki-list',
        '--ignore-ssl-errors',
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-gpu',
        '--window-size=1920,1080'
      ]
    });

    // 创建新页面
    const page = await browser.newPage();
    
    // 设置请求头
    await page.setExtraHTTPHeaders({
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'
    });

    // 导航到登录页面
    console.log('正在导航到登录页面...');
    await page.goto(url, {
      waitUntil: ['domcontentloaded', 'networkidle0'],
      timeout: 60000
    });

    // 等待页面加载完成并截图
    await new Promise(resolve => setTimeout(resolve, 2000));
    await page.screenshot({ path: 'powerone-login-page.png', fullPage: true });
    console.log('登录页面已保存为: powerone-login-page.png');
    
    // 获取页面标题
    const pageTitle = await page.title();
    console.log(`页面标题: ${pageTitle}`);

    // 查看页面是否有iframe
    const iframes = await page.frames();
    console.log(`页面包含 ${iframes.length} 个iframe元素`);
    
    // 尝试找到登录表单元素并登录
    try {
      // 查找账号和密码输入框
      console.log('尝试定位登录表单元素...');
      
      // 尝试多种可能的选择器
      const usernameSelectors = [
        'input[placeholder="账号"]',
        'input[name="username"]',
        'input[id="username"]',
        'input[placeholder="用户名"]'
      ];
      
      const passwordSelectors = [
        'input[placeholder="密码"]',
        'input[name="password"]',
        'input[id="password"]'
      ];
      
      const loginButtonSelectors = [
        'button:has-text("登录")',
        'button[type="submit"]',
        'button.login-button',
        '.el-button.el-button--primary'
      ];
      
      let usernameInput = null;
      for (const selector of usernameSelectors) {
        try {
          usernameInput = await page.waitForSelector(selector, { timeout: 2000 });
          if (usernameInput) {
            console.log(`找到账号输入框: ${selector}`);
            break;
          }
        } catch (error) {
          // 继续尝试下一个选择器
        }
      }
      
      let passwordInput = null;
      for (const selector of passwordSelectors) {
        try {
          passwordInput = await page.waitForSelector(selector, { timeout: 2000 });
          if (passwordInput) {
            console.log(`找到密码输入框: ${selector}`);
            break;
          }
        } catch (error) {
          // 继续尝试下一个选择器
        }
      }
      
      let loginButton = null;
      for (const selector of loginButtonSelectors) {
        try {
          loginButton = await page.waitForSelector(selector, { timeout: 2000 });
          if (loginButton) {
            console.log(`找到登录按钮: ${selector}`);
            break;
          }
        } catch (error) {
          // 继续尝试下一个选择器
        }
      }
      
      // 如果找到输入框，尝试输入凭据并登录
      if (usernameInput && passwordInput && loginButton) {
        console.log('准备输入登录凭据...');
        
        // 这里使用示例凭据，实际使用时需要替换为有效凭据
        await usernameInput.type('admin');
        await passwordInput.type('admin123');
        
        // 保存填写后的截图
        await page.screenshot({ path: 'powerone-filled-form.png', fullPage: true });
        console.log('填写凭据后的页面已保存为: powerone-filled-form.png');
        
        // 点击登录按钮
        console.log('点击登录按钮...');
        await Promise.all([
          page.waitForNavigation({ waitUntil: ['domcontentloaded', 'networkidle0'], timeout: 60000 }),
          loginButton.click()
        ]);
        
        // 登录后截图
        await new Promise(resolve => setTimeout(resolve, 3000));
        await page.screenshot({ path: 'powerone-logged-in.png', fullPage: true });
        console.log('登录成功后的页面已保存为: powerone-logged-in.png');
        
        // 获取登录后的页面标题
        const loggedInTitle = await page.title();
        console.log(`登录后页面标题: ${loggedInTitle}`);
        
        console.log('✅ 登录流程完成！');
      } else {
        console.log('❌ 无法找到登录表单元素，请检查选择器或页面结构');
        
        // 保存页面HTML以进行进一步分析
        const htmlContent = await page.content();
        fs.writeFileSync('powerone-page-html.txt', htmlContent);
        console.log('页面HTML内容已保存为: powerone-page-html.txt');
      }
    } catch (error) {
      console.error('登录过程中发生错误:', error.message);
      await page.screenshot({ path: 'powerone-login-error.png', fullPage: true });
      console.log('错误页面已保存为: powerone-login-error.png');
    }
    
    // 等待一段时间后关闭浏览器
    await new Promise(resolve => setTimeout(resolve, 5000));
    await browser.close();
    console.log('浏览器已关闭');
  } catch (error) {
    console.error('执行过程中发生错误:', error.message);
  }
}

// 执行登录脚本
poweroneLogin();